package com.util;

import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtils {

	/**
	 * Resize image by file Name
	 * @author Michael,Mar 7, 2012
	 * @param infile
	 * @param outfile: default same as infile
	 * @param width: max image width
	 * @param height: max image height
	 * @param quality: default 70, max 100, min 40
	 * @param magnify: whether allow magnify image, default not allow.
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void resize(String infile, String outfile, int width,
			int height, Integer quality, Boolean magnify) throws IOException, InterruptedException {
		
		if(quality == null || quality > 100){
			quality = 100;
		}else if (quality < 40) {
			quality = 40;
		}
		
		if(outfile == null){
			outfile = infile;
		}

		if(magnify == null){
			magnify = false;
		}
		
		BufferedImage thumbImage = null;
		BufferedOutputStream out = null;
		Image image = null;
		image = Toolkit.getDefaultToolkit().createImage(infile);
		MediaTracker mediaTracker = new MediaTracker(new Container());
		mediaTracker.addImage(image, 0);
		mediaTracker.waitForID(0);
		int thumbWidth = width;
		int thumbHeight = height;
		double thumbRatio = (double) thumbWidth / (double) thumbHeight;
		int imageWidth = image.getWidth(null);
		int imageHeight = image.getHeight(null);
		if(!magnify && imageWidth < width && imageHeight < height ){
			System.out.println("image smaller than max do nothing ...");
			return;
		}
		double imageRatio = (double) imageWidth / (double) imageHeight;
		if (thumbRatio < imageRatio) {
			thumbHeight = (int) (thumbWidth / imageRatio);
		} else {
			thumbWidth = (int) (thumbHeight * imageRatio);
		}
		thumbImage = new BufferedImage(thumbWidth, thumbHeight,	BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2D = thumbImage.createGraphics();
		graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
		out = new BufferedOutputStream(new FileOutputStream(outfile));
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
		quality = Math.max(0, Math.min(quality, 100));
		param.setQuality((float) quality / 100.0f, false);
		encoder.setJPEGEncodeParam(param);
		encoder.encode(thumbImage);
		out.close();
		thumbImage = null;
		out = null;
		image = null;
	}
	
	
	
	 /**
	  * Cut Image
	  * @author Michael,Mar 7, 2012
	  * @param srcImageFile
	  * @param x, start point x
	  * @param y, start point y
	  * @param destWidth, cut with
	  * @param destHeight, cut height
	  */
    public static void cut(String srcImageFile, int x, int y, int destWidth,int destHeight) {
        try {
            Image img;
            ImageFilter cropFilter;
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getWidth(); // 源图宽度
            int srcHeight = bi.getHeight(); // 源图高度
            System.out.println("srcWidth= " + srcWidth + "\tsrcHeight= "
                    + srcHeight);
            if (srcWidth >= destWidth && srcHeight >= destHeight) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight,
                        Image.SCALE_DEFAULT);
                // 改进的想法:是否可用多线程加快切割速度
                // 四个参数分别为图像起点坐标和宽高
                // 即: CropImageFilter(int x,int y,int width,int height)
                cropFilter = new CropImageFilter(x, y, destWidth, destHeight);
                img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(), cropFilter));
                BufferedImage tag = new BufferedImage(destWidth, destHeight,
                        BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, null); // 绘制缩小后的图
                g.dispose();
                // 输出为文件
                ImageIO.write(tag, "JPEG", new File(srcImageFile));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}